package xiaopiya.robot.system;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.packet.Presence;
import org.springframework.core.io.Resource;

import xiaopiya.robot.IMessageSender;

/**
 * @author Ray (ayufox@gmail.com)
 * @version 0.1
 */
public class DefaultRosterHandler implements IRosterHandler
{
	private final static Log LOG = LogFactory
			.getLog(DefaultRosterHandler.class);

	private String notice;

	private IFriendService friendService;

	private IMessageSender messageSender;

	public void setFirstimeNoticeFile(Resource firstimeNoticeFile)
			throws IOException
	{
		if (firstimeNoticeFile != null
				&& firstimeNoticeFile.getInputStream() != null)
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			IOUtils.copy(firstimeNoticeFile.getInputStream(), baos);
			this.notice = new String(baos.toByteArray(), "utf-8");
		}
	}

	public void setFriendService(IFriendService friendService)
	{
		this.friendService = friendService;
	}

	public void setMessageSender(IMessageSender messageSender)
	{
		this.messageSender = messageSender;
	}

	public void startup(String robot, Roster roster)
	{
		if (LOG.isInfoEnabled())
		{
			LOG.info("start up[" + roster + "]");
		}

		if (roster.getEntryCount() > 0)
		{
			Collection<RosterEntry> entries = roster.getEntries();
			List<Friend> friends = new ArrayList<Friend>();
			for (RosterEntry entry : entries)
			{
				friends.add(new Friend(entry.getUser(), entry.getName()));
			}

			this.friendService.init(robot, friends);
		}
	}

	public void addFriend(RosterEntry entry)
	{
		if (LOG.isInfoEnabled())
		{
			LOG.info("updateFriend[" + entry + "]");
		}

		this.friendService.addFriend(new Friend(entry.getUser(), entry
				.getName()));

		if (this.notice != null)
		{
			this.messageSender.send(entry.getUser(), this.notice);
		}
	}

	public void removeFriend(RosterEntry entry)
	{
		if (LOG.isInfoEnabled())
		{
			LOG.info("removeFriend[" + entry + "]");
		}

		this.friendService.removeFriend(entry.getUser());
	}

	public void updatePresence(Presence presence)
	{
		if (LOG.isInfoEnabled())
		{
			LOG.info("updatePresence[" + presence + "] for ["
					+ presence.getFrom() + "]");
		}
	}
}
